from wx_login import WechatLogin
from generate import ReportGenerator
import utils
import threading
import random
import requests
import json
import os
from urllib3.exceptions import InsecureRequestWarning

requests.urllib3.disable_warnings(InsecureRequestWarning)

# 查询迁移发票信息
def get_info(thread=8):
    library = utils.default_library()
    account_chunks = library.get_account_chunks(thread)
    chunk_count = 1
    print('查询迁移发票')
    for chunk in account_chunks:
        print('=第{}批线程开始='.format(chunk_count))
        pool = []
        for gh_id in chunk:
            account = library.get_account_data(gh_id)
            thread = GetTransferInvoice(account)
            thread.start()
            pool.append(thread)
        for thread in pool:
            thread.join()
        print('=第{}/{}批线程结束='.format(chunk_count, len(account_chunks)))
        chunk_count += 1
    print('=生成报告=')
    reporter = ReportGenerator(library, utils.get_today())
    reporter.make_transfer_invoice()
    input('=运行结束，按回车键退出=')


# 获取迁移发票信息
class GetTransferInvoice(threading.Thread):
    def __init__(self, account):
        threading.Thread.__init__(self)
        self.account = account

    def run(self):
        os.makedirs('迁移发票', exist_ok=True)
        wlogin = WechatLogin(self.account['gh_id'], self.account['pwd'])
        re_url, session = wlogin.get_session_with_cookie()

        resp = session.get('{0}&f=json&ajax=1&random={1}'.format(re_url, random.random()), verify=False)
        try:
            res = resp.json()
            if res['base_resp']['err_msg'] == 'ok':
                if 'acct_transfer' in res:
                    transfer_status = utils.get_transfer_status(res['acct_transfer']['transfer_status'])  # 迁移状态
                    order_detail = json.loads(res['acct_transfer']['order_detail'])  # 订单详情
                    invoice_status = utils.get_makeout_status(order_detail['invoice_status'])  # 开票状态
                    invoice = json.loads(res['acct_transfer']['invoice'])  # 发票信息
                    invoice_type = utils.get_invoice_type(invoice['invoice_type'])  # 发票类型

                    # 下载发票
                    if 'busi_id' in order_detail and 'einvoice_copy' in order_detail:
                        busi_id = 'transfer_' + order_detail['busi_id'][:-4] 
                        einvoice_copy = order_detail['einvoice_copy']
                        url = "https://mp.weixin.qq.com/cgi-bin/filetransfer?action=multimedia&ticket_id={0}&" \
                              "ticket=&id={1}&token=&lang=zh_CN".format(busi_id, einvoice_copy)
                        rr = session.get(url, verify=False)
                        with open('迁移发票/{0}.pdf'.format(self.account['gh_id']), 'wb') as f:
                            f.write(rr.content)
                    data = [transfer_status, invoice_type, invoice_status]
                else:
                    data = ['无数据', '无数据', '无数据']
                with utils.open_write_data_file(self.account['gh_id'], 'transfer_invoice.json') as f:
                    json.dump(data, f)
            else:
                utils.log_error('{}迁移发票信息查询失败'.format(self.account['gh_id']), 'log')
        except (KeyError, ValueError, TypeError):
            utils.log_error(resp.content, 'log')
        # with utils.open_write_data_file(self.account['gh_id'], 'transfer_invoice.json') as f:
        #     json.dump(data, f)


if __name__ == '__main__':
    print('开始')
    get_info()
